//src/store/authSlice
import { createSlice } from '@reduxjs/toolkit';

const initialState = {
    token: null,
    account: null,
    password: null,
    role: null,
    username: null,
    createdAt: null,
};

const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        setToken: (state, action) => {
            state.token = action.payload.token;
            state.account = action.payload.account;
            state.password = action.payload.password; // 注意：实际应用中应避免存储密码
            state.role = action.payload.role;
            state.username = action.payload.username;
            state.createdAt = action.payload.createdAt
            localStorage.setItem('auth_token', action.payload.token);
            localStorage.setItem('auth_account', action.payload.account);
            localStorage.setItem('auth_password', action.payload.password); // 注意：实际应用中应避免存储密码
            localStorage.setItem('auth_role', action.payload.role);
            localStorage.setItem('auth_username', action.payload.username);
            localStorage.setItem('auth_createdAt', action.payload.createdAt);
        },
        clearToken: (state) => {
            state.token = null;
            state.account = null;
            state.password = null;
            state.role = null;
            state.username = null;
            localStorage.removeItem('auth_token');
            localStorage.removeItem('auth_account');
            localStorage.removeItem('auth_password'); // 注意：实际应用中应避免存储密码
            localStorage.removeItem('auth_role');
            localStorage.removeItem('auth_username');
            localStorage.removeItem('auth_createdAt');
        },
        loadTokenFromStorage: (state) => {
            const token = localStorage.getItem('auth_token');
            const account = localStorage.getItem('auth_account');
            const password = localStorage.getItem('auth_password'); // 注意：实际应用中应避免存储密码
            const role = localStorage.getItem('auth_role');
            const username = localStorage.getItem('auth_username');
            const createAt = localStorage.getItem('auth_createdAt');
            if (token) {
                state.token = token;
            }
            if (account) {
                state.account = account;
            }
            if (password) {
                state.password = password; // 注意：实际应用中应避免存储密码
            }
            if (role) {
                state.role = role;
            }
            if (username) {
                state.username = username;
            }
            if (createAt){
                state.createdAt = createAt
            }
        },
    },
});

export const { setToken, clearToken, loadTokenFromStorage } = authSlice.actions;
export default authSlice.reducer;
